import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface UserInfo {
  id: string
  username: string
  nickname: string
  avatar: string
  email: string
  phone: string
  department: string
  role: string
  permissions: string[]
  lastLoginTime: string
}

export const useUserStore = defineStore('user', () => {
  // 用户状态
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')
  const isAuthenticated = ref(false)
  
  // 用户偏好设置
  const preferences = ref({
    language: 'zh-CN',
    timezone: 'Asia/Shanghai',
    dateFormat: 'YYYY-MM-DD',
    timeFormat: 'HH:mm:ss'
  })
  
  // 计算属性
  const hasRole = computed(() => {
    return (role: string) => userInfo.value?.role === role
  })
  
  const hasPermission = computed(() => {
    return (permission: string) => {
      return userInfo.value?.permissions?.includes(permission) || false
    }
  })
  
  const displayName = computed(() => {
    return userInfo.value?.nickname || userInfo.value?.username || '未知用户'
  })
  
  // Actions
  const setUserInfo = (info: Partial<UserInfo>) => {
    if (userInfo.value) {
      Object.assign(userInfo.value, info)
    } else {
      userInfo.value = info as UserInfo
    }
  }
  
  const setAuthenticated = (status: boolean) => {
    isAuthenticated.value = status
  }
  
  const setToken = (newToken: string) => {
    token.value = newToken
  }
  
  const updateUserInfo = (updates: Partial<UserInfo>) => {
    if (userInfo.value) {
      Object.assign(userInfo.value, updates)
    }
  }
  
  const updatePreferences = (updates: Partial<typeof preferences.value>) => {
    Object.assign(preferences.value, updates)
  }
  
  const login = async (credentials: { username: string; password: string }) => {
    try {
      // 模拟登录请求
      const mockUserInfo: UserInfo = {
        id: '1',
        username: credentials.username,
        nickname: '系统管理员',
        avatar: '/default-avatar.png',
        email: 'admin@crm-travel.com',
        phone: '13800138000',
        department: '技术部',
        role: 'admin',
        permissions: ['*'],
        lastLoginTime: new Date().toISOString()
      }
      
      setUserInfo(mockUserInfo)
      setToken('mock-token-' + Date.now())
      setAuthenticated(true)
      
      return { success: true, message: '登录成功' }
    } catch (error) {
      return { success: false, message: '登录失败' }
    }
  }
  
  const logout = () => {
    userInfo.value = null
    token.value = ''
    isAuthenticated.value = false
    localStorage.removeItem('remember-login')
  }
  
  const refreshUserInfo = async () => {
    // 刷新用户信息的逻辑
    if (userInfo.value) {
      userInfo.value.lastLoginTime = new Date().toISOString()
    }
  }
  
  const init = () => {
    // 检查本地存储的登录状态
    const rememberLogin = localStorage.getItem('remember-login')
    const isDev = import.meta.env.DEV
    
    if (rememberLogin || isDev) {
      // 模拟自动登录（开发环境默认自动登录）
      const mockUserInfo: UserInfo = {
        id: '1',
        username: 'admin',
        nickname: '系统管理员',
        avatar: '',
        email: 'admin@crm-travel.com',
        phone: '13800138000',
        department: '技术部',
        role: 'admin',
        permissions: ['*'],
        lastLoginTime: new Date().toISOString()
      }
      
      setUserInfo(mockUserInfo)
      setAuthenticated(true)
      setToken('dev-token-' + Date.now())
    }
  }
  
  return {
    // State
    userInfo,
    token,
    isAuthenticated,
    preferences,
    
    // Getters
    hasRole,
    hasPermission,
    displayName,
    
    // Actions
    setUserInfo,
    setAuthenticated,
    setToken,
    updateUserInfo,
    updatePreferences,
    login,
    logout,
    refreshUserInfo,
    init
  }
})